package com.xz.knowledgeDuplication.pattern.framework.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 存储和管理多个PropertyValue对象
 *
 * @author 召
 * @date 2022-04-07 21:26:49
 */
public class MutablePropertyValues implements Iterable<PropertyValue> {

    private final List<PropertyValue> propertyValueList;

    public MutablePropertyValues() {
        this.propertyValueList = new ArrayList<PropertyValue>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
        if (propertyValueList == null) {
            this.propertyValueList = new ArrayList<PropertyValue>();
        } else {
            this.propertyValueList = propertyValueList;
        }
    }

    /**
     * 获取PropertyValue类型数组
     *
     * @return 数组
     */
    public PropertyValue[] getPropertyValues() {
        return this.propertyValueList.toArray(new PropertyValue[0]);
    }

    /**
     * 根据propertyName获取对应的PropertyValue
     *
     * @param propertyName property名称
     * @return PropertyValue对象
     */
    public PropertyValue getPropertyValue(String propertyName) {
        for (PropertyValue propertyValue : this.propertyValueList) {
            if (propertyValue.getName().equals(propertyName)) {
                return propertyValue;
            }
        }
        return null;
    }

    /**
     * 添加PropertyValue对象
     *
     * @param propertyValue propertyValue
     * @return 返回MutablePropertyValues便于链式编程
     */
    public MutablePropertyValues addPropertyValue(PropertyValue propertyValue) {
        for (int i = 0; i < this.propertyValueList.size(); i++) {
            PropertyValue value = propertyValueList.get(i);
            if (value.getName().equals(propertyValue.getName())) {
                this.propertyValueList.set(i, propertyValue);
                return this;
            }
        }
        this.propertyValueList.add(propertyValue);
        return this;
    }
    
    /**
     * 判断是否为空
     *
     * @return 是否为空
     */
    public boolean isEmpty() {
        return this.propertyValueList.isEmpty();
    }

    /**
     * 根据propertyName判断是否存在
     *
     * @param propertyName property名称
     * @return 是否存在
     */
    public boolean contains(String propertyName) {
        return this.getPropertyValue(propertyName) != null;
    }

    /**
     * 获取迭代器(迭代器模式)
     *
     * @return 迭代器
     */
    @Override
    public Iterator<PropertyValue> iterator() {
        return this.propertyValueList.iterator();
    }
}
